package com.example.taobaounion.presenter.impl;

import com.example.taobaounion.model.Api;
import com.example.taobaounion.model.bean.Histories;
import com.example.taobaounion.model.bean.SearchRecommend;
import com.example.taobaounion.model.bean.SearchResult;
import com.example.taobaounion.presenter.ISearchPresenter;
import com.example.taobaounion.utils.JsonCacheUtil;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.RetrofitManager;
import com.example.taobaounion.view.ISearchPageCallback;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SearchPresenterImpl implements ISearchPresenter {

    private final Api mApi;
    private ISearchPageCallback mSearchViewCallback=null;
    private static final int DEFAULT_PAGE=0;
    private String mCurrentKeyword=null;
    /**
     * 搜索的当前页面
     */
    private int mCurrentPage=DEFAULT_PAGE;

    public static final String KEY_HISTORIES="key_histories";

    public static final int DEFAULT_HISTORIES_SIZE=10;
    private int mHistoriesMaxSize=DEFAULT_HISTORIES_SIZE;
    private final JsonCacheUtil mJsonCacheUtil;

    public SearchPresenterImpl() {
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        mApi = retrofit.create(Api.class);
        mJsonCacheUtil = JsonCacheUtil.getInstance();
    }

    @Override
    public void getHistories() {
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onHistoriesLoaded(histories);
        }
    }

    @Override
    public void delHistories() {
        mJsonCacheUtil.delCache(KEY_HISTORIES);
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onHistoriesDeleted();
        }

    }

    public void saveHistory(String history){
        //delHistories();
        //获取之前已经保存的数据
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        //如果说已经在了，就干掉，然后再添加
        List<String> historiesList=null;
        if(histories!=null&&histories.getHistories()!=null){
            historiesList=histories.getHistories();
            if(historiesList.contains(history)){
                historiesList.remove(history);
            }
        }
        //去重完成
        //处理没有数据的情况
        if(historiesList==null){
            historiesList=new ArrayList<>();
        }
        if(histories==null){
            histories=new Histories();
        }
        histories.setHistories(historiesList);
        //对个数进行限制
        if(historiesList.size()>mHistoriesMaxSize){
            historiesList=historiesList.subList(0,mHistoriesMaxSize);
        }
        //添加记录
        historiesList.add(history);
        LogUtils.d(this,"histories的值-->"+histories.getHistories());
        //保存记录
        mJsonCacheUtil.saveCache(KEY_HISTORIES,histories);
        //List集合转Json字符串是[毛衣]是一个数组不满足后面的fromJson方法第一个参数是一个对象，所以要传histories
    }


    @Override
    public void doSearch(String keyword) {
        if(mCurrentKeyword==null||!mCurrentKeyword.equals(keyword)){
            this.saveHistory(keyword);
            this.mCurrentKeyword=keyword;
        }
        //更新UI状态
        if(mSearchViewCallback!=null){
             mSearchViewCallback.onLoading();
        }
        Call<SearchResult> task = mApi.doSearch(mCurrentPage, keyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code=response.code();
                LogUtils.d(SearchPresenterImpl.this,"do search result code-->"+code);
                if(code==HttpURLConnection.HTTP_OK){
                    SearchResult result = response.body();
                    handleSearchResult(result);
                }else {
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                t.printStackTrace();
                onError();
            }
        });
    }

    private boolean isResultEmpty(SearchResult result){
        try {
            return result==null||result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size()==0;
        }catch (Exception e){//通过try--catch这样的话防止当你上面的多个对象.方法当出现为null时会报异常走catch方法返回false
            return false;
        }
    }

    private void onError() {
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onError();
        }

    }

    private void handleSearchResult(SearchResult result) {
        if (mSearchViewCallback != null) {
            if(isResultEmpty(result)){
                //数据为空
                mSearchViewCallback.onEmpty();
            }else {
                mSearchViewCallback.onSearchSuccess(result);
            }
        }

    }


    @Override
    public void reSearch() {//记下关键字即可
         if(mCurrentKeyword==null){
             if(mSearchViewCallback!=null){
                 mSearchViewCallback.onEmpty();
             }
         }else {
             //可以重新加载
             doSearch(mCurrentKeyword);
         }
    }

    @Override
    public void loaderMore(){
        mCurrentPage++;
        //进行搜索
        if (mCurrentKeyword==null){
            if (mSearchViewCallback != null) {
                mSearchViewCallback.onEmpty();
            }
        }else {
            //做搜索的事情
            doSearchMore();
        }

    }

    private void doSearchMore() {
        Call<SearchResult> task = mApi.doSearch(mCurrentPage, mCurrentKeyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code=response.code();
                LogUtils.d(SearchPresenterImpl.this,"do search result code-->"+code);
                if(code==HttpURLConnection.HTTP_OK){
                    SearchResult result = response.body();
                    handleMoreSearchResult(result);
                }else {
                    onLoaderMoreError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                onLoaderMoreError();
            }
        });
    }

    /**
     * 处理加载更多的结果
     * @param result
     */
    private void handleMoreSearchResult(SearchResult result) {
        if (mSearchViewCallback != null) {
            if(isResultEmpty(result)){
                //数据为空
                mSearchViewCallback.onEmpty();
            }else {
                mSearchViewCallback.onMoreLoaded(result);
            }
        }
    }

    /**
     * 加载更多内容失败
     */
    private void onLoaderMoreError() {
        mCurrentPage--;
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onMoreLoadedError();
        }
    }

    @Override
    public void getRecommendWords() {
        Call<SearchRecommend> task = mApi.getRecommendWords();
        task.enqueue(new Callback<SearchRecommend>() {
            @Override
            public void onResponse(Call<SearchRecommend> call, Response<SearchRecommend> response) {
                int code = response.code();
                LogUtils.d(SearchPresenterImpl.this,"getRecommendWords result code---->"+code);
                if(code== HttpURLConnection.HTTP_OK){
                    //处理结果
                    SearchRecommend result = response.body();
                    if (mSearchViewCallback != null) {
                        mSearchViewCallback.onRecommendWordsLoaded(result.getData());
                    }
                }else {
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchRecommend> call, Throwable t) {
                onError();
                t.printStackTrace();
            }
        });
    }

    @Override
    public void registerViewCallback(ISearchPageCallback callback) {
           this.mSearchViewCallback=callback;
    }

    //还要记得取消注册，因为当你在SearchFragment如果还不对其取消注册的回调接口的话，可能会出现的情况是
    //当你销毁了SearchFragment时此时实现类的mSearchViewCallback还持有SearchFragment的引用还在调用
    // SearchFragment的有关方法会造成内存泄露（你已经销毁了SearchFragment还调得到其方法吗？调不到如果调会造成内存泄露），
    // 所以要制成null，防止其调用。
    @Override
    public void unregisterViewCallback(ISearchPageCallback callback) {
           this.mSearchViewCallback=null;
    }
}
